package com.atguigu.ggkt.live.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.ggkt.client.couser.CourseFeignClient;
import com.atguigu.ggkt.client.user.UserInfoFeignClient;
import com.atguigu.ggkt.exception.GgktException;
import com.atguigu.ggkt.live.mtcloud.CommonResult;
import com.atguigu.ggkt.live.mtcloud.MTCloud;
import com.atguigu.ggkt.live.service.*;
import com.atguigu.ggkt.model.live.*;
import com.atguigu.ggkt.live.mapper.LiveCourseMapper;
import com.atguigu.ggkt.model.user.UserInfo;
import com.atguigu.ggkt.model.vod.Teacher;
import com.atguigu.ggkt.utils.DateUtil;
import com.atguigu.ggkt.vo.live.LiveCourseConfigVo;
import com.atguigu.ggkt.vo.live.LiveCourseFormVo;
import com.atguigu.ggkt.vo.live.LiveCourseGoodsView;
import com.atguigu.ggkt.vo.live.LiveCourseVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 直播课程表 服务实现类
 * </p>
 *
 * @author sleephardzz
 * @since 2023-07-29
 */
@Service
public class LiveCourseServiceImpl extends ServiceImpl<LiveCourseMapper, LiveCourse> implements LiveCourseService {
    @Autowired
    private CourseFeignClient courseFeignClient;
    @Autowired
    private MTCloud mtCloud;
    @Autowired
    private LiveCourseDescriptionService liveCourseDescriptionService;
    @Autowired
    private LiveCourseAccountService liveCourseAccountService;
    @Autowired
    private LiveCourseConfigService liveCourseConfigService;
    @Autowired
    private LiveCourseGoodsService liveCourseGoodsService;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;
    //获得直播内容的详细信息
    @Override
    public Map<String, Object> getInfoById(Long courseId) {
        //获得直播课程对象：封装开始和结束时间
        LiveCourse liveCourse = this.getById(courseId);
        liveCourse.getParam().put("startTimeString", new DateTime(liveCourse.getStartTime()).toString("yyyy年MM月dd HH:mm"));
        liveCourse.getParam().put("endTimeString", new DateTime(liveCourse.getEndTime()).toString("yyyy年MM月dd HH:mm"));
        //获得老师对象
        Teacher teacher = courseFeignClient.getTeacherInfo(liveCourse.getTeacherId());
        //获得课程对象详细描述
        LiveCourseDescription liveCourseDescription = liveCourseDescriptionService.getLiveCourseDescriptionById(courseId);
        //封装：返回map集合
        Map<String, Object> map = new HashMap<>();
        map.put("liveCourse", liveCourse);
        map.put("liveStatus", this.getLiveStatus(liveCourse));
        map.put("teacher", teacher);
        if(null != liveCourseDescription) {
            map.put("description", liveCourseDescription.getDescription());
        } else {
            map.put("description", "");
        }
        return map;
    }
    //根据直播id获取access——token
    @Override
    public JSONObject getAccessToken(Long courseId, Long userId) throws Exception {
        //根据课程id获取直播课程信息
        LiveCourse liveCourse = baseMapper.selectById(courseId);
        //根据用户id获取用户信息
        UserInfo userInfo = userInfoFeignClient.getById(userId);

        HashMap<Object, Object> hashMap = new HashMap<>();
        /**
         * 进入一个课程
         *
         *  course_id      课程ID
         *  uid            用户唯一ID
         *  nickname       用户昵称
         *  role           用户角色，枚举见:ROLE 定义
         *     expire         有效期,默认:3600(单位:秒)
         *   options        可选项，包括:gender:枚举见上面GENDER定义,avatar:头像地址
         */
        String res = mtCloud.courseAccess(liveCourse.getCourseId().toString(),
                userId.toString(),
                userInfo.getNickName(),
                MTCloud.ROLE_USER,
                3600,
                hashMap);
        CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
        if(Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
            JSONObject object = commonResult.getData();
            System.out.println("access::"+object.getString("access_token"));
            return object;
        } else {
            throw new GgktException(20001,"获取失败");
        }
    }

    //    @ApiOperation(value = "获取最近的直播列表")
    @Override
    public List<LiveCourseVo> findLatelyList() {
        List<LiveCourseVo> list = baseMapper.getLateList();
        //遍历直播list
        for (LiveCourseVo liveCourseVo : list) {
            liveCourseVo.setStartTimeString(new DateTime(liveCourseVo.getStartTime()).toString("yyyy年MM月dd HH:mm"));
            liveCourseVo.setEndTimeString(new DateTime(liveCourseVo.getEndTime()).toString("HH:mm"));
            //根据讲师id--获得老师对象
            Long teacherId = liveCourseVo.getTeacherId();
            Teacher teacher = courseFeignClient.getTeacherInfo(teacherId);
            liveCourseVo.setTeacher(teacher);
            //修改直播状态
            liveCourseVo.setLiveStatus(this.getLiveStatus(liveCourseVo));
        }
        return list;
    }


    /*** 直播状态 0：未开始 1：直播中 2：直播结束*/
    private int getLiveStatus(LiveCourse liveCourse) {
        // 直播状态 0：未开始 1：直播中 2：直播结束
        int liveStatus = 0;
        Date curTime = new Date();
        if (DateUtil.dateCompare(curTime, liveCourse.getStartTime())) {
            liveStatus = 0;
        } else if (DateUtil.dateCompare(curTime, liveCourse.getEndTime())) {
            liveStatus = 1;
        } else {
            liveStatus = 2;
        }
        return liveStatus;
    }

    //    @ApiOperation(value = "修改直播账号内的配置信息")
    @Override
    public void updateConfig(LiveCourseConfigVo liveCourseConfigVo) throws Exception {
        //1修改表
        LiveCourseConfig liveCourseConfig = new LiveCourseConfig();
        /** 修改-->liveCourseConfigVo，liveCourseConfig
         * 查询：liveCourseConfig，liveCourseConfigVo*/
        BeanUtils.copyProperties(liveCourseConfigVo, liveCourseConfig);
        if (StringUtils.isEmpty(liveCourseConfigVo.getId())) {
            return;
        } else {
            liveCourseConfigService.updateById(liveCourseConfig);
        }
        //2修改商品表
//        2.1先删
        LambdaQueryWrapper<LiveCourseGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(!StringUtils.isEmpty(liveCourseConfigVo.getLiveCourseId()), LiveCourseGoods::getLiveCourseId, liveCourseConfigVo.getLiveCourseId());
        liveCourseGoodsService.remove(wrapper);
//        2.2再加
        if (!CollectionUtils.isEmpty(liveCourseConfigVo.getLiveCourseGoodsList()))
            liveCourseGoodsService.saveBatch(liveCourseConfigVo.getLiveCourseGoodsList());

        //3调用Api改平台内容
        this.updateLiveConfig(liveCourseConfigVo);

    }


    //3调用Api改平台内容
    private void updateLiveConfig(LiveCourseConfigVo liveCourseConfigVo) throws Exception {
        LiveCourse liveCourse = baseMapper.selectById(liveCourseConfigVo.getLiveCourseId());

        //参数设置
        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
        //界面模式
        hashMap.put("pageViewMode", liveCourseConfigVo.getPageViewMode());
        //观看人数开关
        JSONObject number = new JSONObject();
        number.put("enable", liveCourseConfigVo.getNumberEnable());
        hashMap.put("number", number.toJSONString());
        //观看人数开关
        JSONObject store = new JSONObject();
        number.put("enable", liveCourseConfigVo.getStoreEnable());
        number.put("type", liveCourseConfigVo.getStoreType());
        hashMap.put("store", number.toJSONString());
        //商城列表：通过LiveCourseGoodsView获得
        List<LiveCourseGoods> liveCourseGoodsList = liveCourseConfigVo.getLiveCourseGoodsList();
        if (!CollectionUtils.isEmpty(liveCourseGoodsList)) {
            List<LiveCourseGoodsView> liveCourseGoodsViewList = new ArrayList<>();
            for (LiveCourseGoods liveCourseGoods : liveCourseGoodsList) {
                LiveCourseGoodsView liveCourseGoodsView = new LiveCourseGoodsView();
                BeanUtils.copyProperties(liveCourseGoods, liveCourseGoodsView);
                liveCourseGoodsViewList.add(liveCourseGoodsView);
            }
            JSONObject goodsListEdit = new JSONObject();
            goodsListEdit.put("status", "0");
            hashMap.put("goodsListEdit ", goodsListEdit.toJSONString());
            hashMap.put("goodsList", JSON.toJSONString(liveCourseGoodsViewList));
        }
        /**
         * 修改生活直播相关配置
         *
         *   course_id 		课程ID
         *  options 		配置参数
         * @return
         * @throws Exception
         */
        String res = mtCloud.courseUpdateLifeConfig(liveCourse.getCourseId().toString(), hashMap);
        CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
        if (Integer.parseInt(commonResult.getCode()) != MTCloud.CODE_SUCCESS) {
            throw new GgktException(20001, "修改配置信息失败");
        }
    }

    //    @ApiOperation(value = "获取直播账号内的配置信息")
    @Override
    public LiveCourseConfigVo getCourseConfig(Long id) {
        //1根据课程id查询配置信息
        LiveCourseConfig liveCourseConfig = liveCourseConfigService.getCourseConfigByCourseId(id);
        //2封装回 vo
        LiveCourseConfigVo liveCourseConfigVo = new LiveCourseConfigVo();
        if (!StringUtils.isEmpty(liveCourseConfig)) {
            List<LiveCourseGoods> liveCourseGoodsList = liveCourseGoodsService.getGoodsListByCourseId(id);
            BeanUtils.copyProperties(liveCourseConfig, liveCourseConfigVo);
            //封装商品对象
            liveCourseConfigVo.setLiveCourseGoodsList(liveCourseGoodsList);
        }
        return liveCourseConfigVo;
    }


    //@ApiOperation("直播课程添加")
    @Override
    public void saveLiveCourseFormVo(LiveCourseFormVo liveCourseFormVo) throws Exception {
//        LiveCourseFormVo--LiveCourse
        LiveCourse liveCourse = new LiveCourse();
        BeanUtils.copyProperties(liveCourseFormVo, liveCourse);

        //获得老师对象
        Teacher teacher =
                courseFeignClient.getTeacherInfo(liveCourse.getTeacherId());
        /** 调用方法添加直播课程 */
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("scenes", 2);//直播类型。1: 教育直播，2: 生活直播。默认 1，说明：根据平台开通的直播类型填写
        hashMap.put("password", liveCourseFormVo.getPassword());
        /**
         * mtCloud.courseAdd() 增加一个直播课程
         *
         *  course_name 课程名称
         *  account 发起直播课程的主播账号
         *  start_time 课程开始时间,格式: 2015-01-10 12:00:00
         *  end_time 课程结束时间,格式: 2015-01-10 13:00:00
         *  nickname       用户昵称
         *  accountIntro    主播介绍
         *  options     其他参数
         * @return
         */
        String res = mtCloud.courseAdd(liveCourse.getCourseName(),
                teacher.getId().toString(),
                new DateTime(liveCourse.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"),
                new DateTime(liveCourse.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"),
                teacher.getName(),
                teacher.getIntro(),
                hashMap);
        System.out.println("res=" + res);
        CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
        if (Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
            //保存课程基本信息
            JSONObject resultObject = commonResult.getData();//获取添加课程后的结果
            Long course_id = resultObject.getLong("course_id");
            liveCourse.setCourseId(course_id);
            baseMapper.insert(liveCourse);
            //保存课程详情信息
            LiveCourseDescription liveCourseDescription = new LiveCourseDescription();
            liveCourseDescription.setDescription(liveCourseFormVo.getDescription());
            liveCourseDescription.setLiveCourseId(liveCourse.getId());
            liveCourseDescriptionService.save(liveCourseDescription);
            //保存课程账号信息
            LiveCourseAccount liveCourseAccount = new LiveCourseAccount();
            liveCourseAccount.setLiveCourseId(liveCourse.getId());
            liveCourseAccount.setZhuboAccount(resultObject.getString("bid"));
            liveCourseAccount.setZhuboPassword(liveCourseFormVo.getPassword());
            liveCourseAccount.setAdminKey(resultObject.getString("admin_key"));
            liveCourseAccount.setUserKey(resultObject.getString("user_key"));
            liveCourseAccount.setZhuboKey(resultObject.getString("zhubo_key"));
            liveCourseAccountService.save(liveCourseAccount);
        } else {
            throw new GgktException(20001, "直播添加失败");
        }
    }

    //    @ApiOperation(value = "直播课程删除")
    @Override
    public void removeLive(Long id) throws Exception {
        //1查询出课程
        LiveCourse liveCourse = baseMapper.selectById(id);
        //查不到return
        if (StringUtils.isEmpty(liveCourse)) {
            return;
        }
        //2调用方法删除【courseId】
        Long courseId = liveCourse.getCourseId();
        String res = mtCloud.courseDelete(courseId.toString());
        //3 删表
        baseMapper.deleteById(id);
    }

    //    查询课程详细信息
    @Override
    public LiveCourseFormVo getLiveCourseFormVo(Long id) {
        //获取直播课程的基本信息
        LiveCourse liveCourse = baseMapper.selectById(id);
        //获取直播课程的描述信息
        LiveCourseDescription liveCourseDescription = liveCourseDescriptionService.getLiveCourseDescriptionById(id);

        //封装
        LiveCourseFormVo liveCourseFormVo = new LiveCourseFormVo();
        BeanUtils.copyProperties(liveCourse, liveCourseFormVo);
        liveCourseFormVo.setDescription(liveCourseDescription.getDescription());
        return liveCourseFormVo;
    }

    //    ("修改课程内容【包括详情】")
    @Override
    public void updateLiveById(LiveCourseFormVo liveCourseFormVo) throws Exception {
        //根据id获取直播课程基本信息
        LiveCourse liveCourse = baseMapper.selectById(liveCourseFormVo.getId());
        //liveCourseFormVo -- liveCourse
        BeanUtils.copyProperties(liveCourseFormVo, liveCourse);

        HashMap<Object, Object> options = new HashMap<>();
        Teacher teacher =
                courseFeignClient.getTeacherInfo(liveCourse.getTeacherId());
        /**
         * 更新课程信息
         *
         *   course_id 课程ID
         *   account 发起直播课程的主播账号
         *   course_name 课程名称
         *   start_time 课程开始时间,格式:2015-01-01 12:00:00
         *   end_time 课程结束时间,格式:2015-01-01 13:00:00
         *   nickname 	主播的昵称
         *   accountIntro 	主播的简介
         *  options 		可选参数
         */
        String res = mtCloud.courseUpdate(liveCourse.getCourseId().toString(),
                teacher.getId().toString(),
                liveCourse.getCourseName(),
                new DateTime(liveCourse.getStartTime()).toString("yyyy-MM-dd HH:mm:ss"),
                new DateTime(liveCourse.getEndTime()).toString("yyyy-MM-dd HH:mm:ss"),
                teacher.getName(),
                teacher.getIntro(),
                options);

        //返回结果转换，判断是否成功
        CommonResult<JSONObject> commonResult = JSON.parseObject(res, CommonResult.class);
        if (Integer.parseInt(commonResult.getCode()) == MTCloud.CODE_SUCCESS) {
            JSONObject resultObject = commonResult.getData();
            //更新直播课程基本信息
            liveCourse.setCourseId(resultObject.getLong("course_id"));
            baseMapper.updateById(liveCourse);
            //获取课程的详细信息
            LiveCourseDescription liveCourseDescription =
                    liveCourseDescriptionService.getLiveCourseDescriptionById(liveCourse.getId());
            liveCourseDescription.setDescription(liveCourseFormVo.getDescription());
            liveCourseDescriptionService.updateById(liveCourseDescription);
        }
    }


    //直播课程列表获得
    @Override
    public Page<LiveCourse> selectPage(Page<LiveCourse> pageParam) {
        //查询所有 wrapper = null
        Page<LiveCourse> selectPage = baseMapper.selectPage(pageParam, null);
        List<LiveCourse> records = pageParam.getRecords();
        for (LiveCourse lc : records) {
            //老师id
            Long teacherId = lc.getTeacherId();
            //根据老师id查询老师信息
            /** 远程调用实现 */
            Teacher teacher = courseFeignClient.getTeacherInfo(teacherId);
            //封装
            if (!StringUtils.isEmpty(teacher)) {
                lc.getParam().put("teacherName", teacher.getName());
                lc.getParam().put("teacherLevel", teacher.getLevel());
            }
        }
        return selectPage;
    }

}
